package top.revery.task.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import top.revery.api.api.user.IUserKolApi;
import top.revery.api.config.UserPageData;

import top.revery.api.entity.user.BaseUserKol;
import top.revery.task.dto.KolDto;
import top.revery.task.service.KolService;


import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * @author denghao
 * @title
 * @package 网红
 * @date 2019/12/13 11:36
 */
@RestController
@Transactional
public class UserKolController implements IUserKolApi {

    @Autowired
    private KolService kolService;
    @Autowired
    private KolDto kolDto;

    //分页多条件查询所有
    @Override
    public UserPageData getList(int pageNum, int pageSize, Map map) {
        Page<BaseUserKol> pageList = kolService.findPage(pageNum, pageSize, map);
        UserPageData userPageData = new UserPageData();
        userPageData.list = pageList.getContent();
        userPageData.rows = pageList.getTotalElements();
        return userPageData;

    }

    //保存会员
    @Override
    public BaseUserKol save(BaseUserKol baseUserKol) {
        baseUserKol.setAddTime(new Timestamp(new Date().getTime()));
        return kolService.save(baseUserKol);

    }

    //修改会员
    @Override
    public void update(BaseUserKol baseUserKol, Long id) throws Exception {

        try {
            baseUserKol.setId(id);
            String tele = baseUserKol.getTelephone();
            String email = baseUserKol.getEmail();
            if (!tele.matches("^1[^124]\\d{9}$") || !email.matches("^[A-Za-z0-9]+([_\\.][A-Za-z0-9]+)*@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$")) {
                throw new Exception("格式不对！请重新输入！");
            }
            Optional<BaseUserKol> byId = kolDto.findById(id);
            if (!byId.get().getTelephone().equals(baseUserKol.getTelephone())) {
                BaseUserKol baseTel = kolService.findByTelephone(baseUserKol.getTelephone());
                if (baseTel != null) {
                    throw new Exception("输入号码有误！请重新输入！");
                }
            }
            if (!byId.get().getEmail().equals(baseUserKol.getEmail())) {
                BaseUserKol baseEamil = kolService.findByEmail(baseUserKol.getEmail());
                if (baseEamil != null) {
                    throw new Exception("输入邮箱有误！请重新输入！");
                }
            }
            kolService.update(baseUserKol);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public BaseUserKol findById(Long id) {

        return kolDto.findById(id).get();
    }
}
